<!-- 环境-- 首页 -->
<template>
  <div style="display: flex">
    <!-- 左边 -->
    <div style="flex: 3">
      <div style="display: flex; flex-direction: column">
        <!-- 上部 -->
        <div style="flex: 1">
          <div style="display: flex">
            <div style="flex: 9" v-if="!TopDigital.length">
              <div style="color: red; text-align: center; font-size: 20px">页面无数据</div>
            </div>
            <!-- 数据显示 -->
            <div style="flex: 9; display: flex; flex-wrap: wrap" v-else>
              <div
                style="
                  width: 18%;
                  box-sizing: border-box;
                  font-size: 16px;
                  font-weight: 400;
                  margin: 1%;
                  border: 1px solid skyblue;
                  padding: 1%;
                  height: 85px;
                "
                v-for="(item, index) in TopDigital"
                :key="index"
              >
                <div class="text-overflow">
                  {{ item.name }}
                </div>
                <div style="text-align: center; margin-top: 10%">
                  {{ item.value }}
                </div>
              </div>
            </div>
            <!-- 数据选择 -->
            <div style="flex: 1">
              <el-popover placement="left" :width="300" trigger="click">
                <template #reference>
                  <el-button type="primary">请选择需要显示的数据</el-button>
                </template>
                <div class="mt-4" style="height: 80vh">
                  <el-checkbox-group
                    v-model="TopDigitalcheckboxGroup"
                    size="small"
                    style="
                      text-align: center;
                      overflow: hidden;
                      max-height: 80vh;
                      overflow-y: scroll;
                    "
                  >
                    <div v-for="(item, index) in TopDigitalList" :key="index">
                      <el-checkbox
                        :label="item.name"
                        :value="item.id"
                        border
                        @change="handleChangeTopDigital()"
                      />
                      <el-input
                        style="width: 35px; margin-bottom: 4%"
                        size="small"
                        v-model="item.index"
                        @blur="TopDigitalinputBlur(item)"
                      />
                    </div>
                  </el-checkbox-group>
                </div>
              </el-popover>
            </div>
          </div>
        </div>
        <!-- 中部 -->
        <div style="flex: 1">
          <img src="../../assets/FdcIndex.png" alt="" style="width: 100%; height: 400px" />
        </div>
        <!-- 下部 -->
        <div style="flex: 1">
          <div style="display: flex">
            <div style="flex: 9" v-if="!BottomSwitch.length">
              <div style="color: red; text-align: center; font-size: 20px">页面无数据</div>
            </div>
            <!-- 开关显示 -->
            <div style="flex: 9; display: flex; flex-wrap: wrap" v-else>
              <div
                style="
                  width: 18%;
                  box-sizing: border-box;
                  font-size: 16px;
                  font-weight: 400;
                  margin: 1%;
                  border: 1px solid skyblue;
                  padding: 1%;
                  height: 85px;
                "
                v-for="(item, index) in BottomSwitch"
                :key="index"
              >
                <div class="text-overflow">
                  {{ item.name }}
                </div>
                <div style="text-align: center; margin-top: 2%">
                  <el-radio-group v-model="item.value" size="small" @change="changeEvent(item)">
                    <el-radio-button
                      v-for="(item, index) in displayRuleText1(item)"
                      :key="index"
                      :label="item.name"
                      :value="item.value"
                    />
                  </el-radio-group>
                </div>
              </div>
            </div>

            <!-- 右--开关 -->
            <div style="flex: 1">
              <el-popover placement="left" :width="300" trigger="click">
                <template #reference>
                  <el-button type="primary">请选择需要显示的数据</el-button>
                </template>
                <div class="mt-4" style="height: 80vh">
                  <el-checkbox-group
                    v-model="BottomSwitchcheckboxGroup"
                    size="small"
                    style="
                      text-align: center;
                      overflow: hidden;
                      max-height: 80vh;
                      overflow-y: scroll;
                    "
                  >
                    <div v-for="(item, index) in BottomSwitchList" :key="index">
                      <el-checkbox
                        :label="item.name"
                        :value="item.id"
                        border
                        @change="handleChangeBottomSwitch(item.id)"
                      />
                      <el-input
                        style="width: 35px; margin-bottom: 4%"
                        size="small"
                        v-model="item.index"
                        @blur="BottomSwitchinputBlur(item)"
                      />
                    </div>
                  </el-checkbox-group>
                </div>
              </el-popover>
              <div>
                <el-button
                  round
                  :style="{
                    width: '100%',
                    height: '60px',
                    marginTop: '30%',
                    fontSize: '20px',
                    backgroundColor: automaticControlcolor
                  }"
                  @click="automaticControl"
                  >自动控制</el-button
                >
              </div>
              <div>
                <el-button
                  round
                  :style="{
                    width: '100%',
                    height: '60px',
                    marginTop: '30%',
                    fontSize: '20px',
                    backgroundColor: manualControlcolor
                  }"
                  @click="manualControl"
                  >手动控制</el-button
                >
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
    <!-- 右边 -->
    <div style="flex: 1; margin-left: 1%">
      <div>
        <el-table :data="tableData" style="width: 100%" show-overflow-tooltip>
          <el-table-column label="项目名称" width="180" align="center">
            <template #default="scope">
              {{ scope.row.name }}
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template #default="scope">
              <el-button size="small" type="primary" @click="handleDelete(scope.$index, scope.row)"
                >管理</el-button
              >
              <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">
                删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div style="width: 100%">
        <img src="../../assets/fished.jpg" alt="" style="width: 100%" />
      </div>

      <!-- <el-button @click="getDeviceValue">点击</el-button> -->
      <!-- <div style="width: 80%">
        <img src="../../assets/csolution.png" alt="" style="width: 80%" />
      </div>
      <div style="width: 80%">
        <img src="../../assets/csolution.png" alt="" style="width: 80%" />
      </div> -->
      <!-- <div style="width: 80%">
        <img src="../../assets/csolution.png" alt="" style="width: 80%" />
      </div> -->
    </div>
  </div>

  <!-- <el-button @click="getDeviceValue">DDDD</el-button> -->
</template>

<script >
import { ElMessage } from 'element-plus'
import { computed, ref, onMounted, onBeforeUnmount } from 'vue'
import { useStore } from 'vuex'
import template2 from '../../MyJson/AutoRendermod2.json'
import { v4 as uuidv4 } from 'uuid'

export default {
  setup() {
    const tableData = [
      { name: '2号养殖桶' },
      { name: '3号养殖桶' },
      { name: '8号养殖桶' },
      { name: '6号养殖桶' }
    ]

    // 上面显示数字量
    const TopDigital = ref([])
    // 下面显示开关
    const BottomSwitch = ref([])

    // 需要选择的所有变量
    const TopDigitalList = ref([])

    // 需要选择的所有开关
    const BottomSwitchList = ref([])

    // 已选择的变量名称
    const TopDigitalcheckboxGroup = ref([])

    // 已选择的开关名称
    const BottomSwitchcheckboxGroup = ref([])

    // 模板
    const JsonTmp = ref(template2)

    // 定时器
    const timer = ref(null)

    // 自动控制颜色
    const automaticControlcolor = ref(null)

    // 手动控制颜色
    const manualControlcolor = ref(null)

    onMounted(() => {
      // 加载颜色
      loadColor()
      // 加载能勾选的数字量
      loadDigital()

      loadSwitch()
      // 加载 右边选中的数字量
      loadDigitalcheckboxGroup()
      // 加载 右边选中的开关
      // 加载能勾选的开关
      loadSwitchcheckboxGroup()
      getDigitalValue()
      getSwitchValue()
      timer.value = null
      timer.value = setInterval(() => {
        getDigitalValue()
        getSwitchValue()
      }, 1000)
    })

    const displayRuleText1 = computed(() => {
      return (value) => {
        const num = value.rendermod2
        const rule = JsonTmp.value.template[Number(num)]
        return rule
      }
    })

    const displayRuleText2 = computed(() => {
      return (value) => {
        const rule = JsonTmp.value.template[Number(value)]
        return rule[1].name
      }
    })

    // 自动控制
    const automaticControl = () => {
      const res = window.api.changeAutoTmpMode('AUTO_TMP_MODE_AUTO')
      const result = JSON.parse(res)
      if (result.code === '200') {
        ElMessage.success(result.msg)
        automaticControlcolor.value = 'skyblue'
        manualControlcolor.value = '#B0B0B0'
      } else {
        ElMessage.error(result.msg)
      }
    }
    // 手动控制
    const manualControl = () => {
      const res = window.api.changeAutoTmpMode('AUTO_TMP_MODE_MANUAL')
      const result = JSON.parse(res)
      if (result.code === '200') {
        ElMessage.success(result.msg)
        manualControlcolor.value = 'skyblue'
        automaticControlcolor.value = '#B0B0B0'
      } else {
        ElMessage.error(result.msg)
      }
    }
    // 初始化 获取自动手动 颜色
    const loadColor = () => {
      const dds = window.api.getGlobalAutoSchedRanStatus()
      if (dds) {
        automaticControlcolor.value = 'skyblue'
        manualControlcolor.value = '#B0B0B0'
      } else {
        manualControlcolor.value = 'skyblue'
        automaticControlcolor.value = '#B0B0B0'
      }
    }

    //  初始化加载 数字量
    const loadDigital = () => {
      const res = window.api.listPropertyByShowPageType(['DIGITAL'])
      const resList = JSON.parse(res)
      TopDigitalList.value = []
      resList.forEach((item) => {
        if (item.indextype === 'Sys') {
          const dds = {
            id: `${item.deviceId}${item.statusName}`,
            name: item.propertyName,
            indextype: item.indextype,
            index: item.index,
            deviceId: item.deviceId,
            statusName: item.statusName
          }
          TopDigitalList.value.push(dds)
        }
        if (item.indextype === 'Variable') {
          const dds = {
            id: `${item.deviceId}${item.statusName}`,
            name: item.deviceName,
            indextype: item.indextype,
            index: item.index,
            deviceId: item.deviceId,
            statusName: item.statusName
          }
          TopDigitalList.value.push(dds)
        }
        if (item.indextype === 'Timer') {
          const dds = {
            id: `${item.deviceId}${item.statusName}`,
            name: `${item.deviceName}-${item.propertyName}`,
            indextype: item.indextype,
            index: item.index,
            deviceId: item.deviceId,
            statusName: item.statusName
          }
          TopDigitalList.value.push(dds)
        }
        if (item.indextype === 'Counters') {
          const dds = {
            id: `${item.deviceId}${item.statusName}`,
            name: `${item.deviceName}-${item.propertyName}`,
            indextype: item.indextype,
            index: item.index,
            deviceId: item.deviceId,
            statusName: item.statusName
          }
          TopDigitalList.value.push(dds)
        }
        if (item.indextype === 'Device') {
          const dds = {
            id: `${item.deviceId}${item.statusName}`,
            name: `${item.deviceName}-${item.propertyName}`,
            indextype: item.indextype,
            index: item.index,
            deviceId: item.deviceId,
            statusName: item.statusName
          }
          TopDigitalList.value.push(dds)
        }
      })
    }
    // 勾选 数字量 保存值
    const handleChangeTopDigital = () => {
      const list = TopDigitalList.value.filter((item) =>
        TopDigitalcheckboxGroup.value.includes(item.id)
      )
      // console.log(list, ' 勾选 数字量 保存的值', new Date())
      window.api.swapAllIndexDigitalPropertyJsonObj(JSON.stringify(list))
    }
    // 数字量 输入框 索引
    const TopDigitalinputBlur = (data) => {
      window.api.updatePropertyByJsonObj(data.deviceId, data.name, 'index', data.index)
      handleChangeTopDigital()
    }
    // 数字量 时时获取值
    const getDigitalValue = () => {
      TopDigital.value = []
      const dds = window.api.listIndexDigitalPropertyToJsonArr()
      const tagList = JSON.parse(dds)
      // console.log(tagList, '数字量 时时获取值', new Date())
      tagList.forEach((item) => {
        let res = {
          name: '',
          id: `${item.deviceId}${item.statusName}`,
          value: item.value || item.value === 0 ? item.value : 'NAN'
        }

        if (item.deviceId === '1234567890') {
          res.name = item.propertyName
        } else if (item.indextype === 'Device' || item.indextype === 'Counters') {
          res.name = `${item.deviceName}-${item.propertyName}`
        } else if (item.indextype === 'Timer') {
          res.name = `${item.deviceName}-${item.propertyName}`
          res.value = item.value || item.value === 0 ? computedvalue(item.value) : 'NAN'
        } else {
          res.name = item.deviceName
        }
        TopDigital.value.push(res)
      })
    }
    // 加载 checkboxGroup
    const loadDigitalcheckboxGroup = () => {
      TopDigitalcheckboxGroup.value = []
      const dds = window.api.listIndexDigitalPropertyToJsonArr()
      const tagList = JSON.parse(dds)
      tagList.forEach((item) => {
        TopDigitalcheckboxGroup.value.push(`${item.deviceId}${item.statusName}`)
      })
    }

    // 初始化加载 开关
    const loadSwitch = () => {
      const result = window.api.listPropertyByShowPageType(['SWITCH'])
      const resultList = JSON.parse(result)
      resultList.forEach((item) => {
        if (item.indextype === 'Device') {
          const dds = {
            id: `${item.deviceId}${item.statusName}`,
            name: `${item.deviceName}-${item.propertyName}`,
            indextype: item.indextype,
            index: item.index,
            deviceId: item.deviceId,
            statusName: item.statusName
          }
          BottomSwitchList.value.push(dds)
        }
      })
    }
    // 勾选 开关 保存值
    const handleChangeBottomSwitch = () => {
      const list = BottomSwitchList.value.filter((item) =>
        BottomSwitchcheckboxGroup.value.includes(item.id)
      )
      window.api.swapAllIndexSwitchPropertyJsonObj(JSON.stringify(list))
    }
    // 开关 输入框 索引
    const BottomSwitchinputBlur = (data) => {
      window.api.updatePropertyByJsonObj(data.deviceId, data.name, 'index', data.index)
      handleChangeBottomSwitch()
    }
    // 开关 时时获取值
    const getSwitchValue = () => {
      BottomSwitch.value = []
      const dds = window.api.listIndexSwitchPropertyToJsonArr()
      const tagList = JSON.parse(dds)
      tagList.forEach((item) => {
        const res = {
          name: `${item.deviceName}-${item.statusName}`,
          id: `${item.deviceId}${item.statusName}`,
          value: item.value,
          rendermod2: item.rendermod2,
          deviceId: item.deviceId,
          propertyName: item.propertyName
        }
        BottomSwitch.value.push(res)
      })
    }
    // 加载 checkboxGroup
    const loadSwitchcheckboxGroup = () => {
      BottomSwitchcheckboxGroup.value = []
      const dds = window.api.listIndexSwitchPropertyToJsonArr()
      const tagList = JSON.parse(dds)
      tagList.forEach((item) => {
        BottomSwitchcheckboxGroup.value.push(`${item.deviceId}${item.statusName}`)
      })
    }
    // 操作开关
    const changeEvent = (data) => {
      window.api.operateDevice(data.deviceId, data.propertyName, data.value)
    }
    // 秒 转 时分秒
    const computedvalue = (seconds) => {
      // 将毫秒转换为秒
      const totalSeconds = seconds / 1000

      // 计算小时
      const hours = Math.floor(totalSeconds / 3600)
      // 计算剩余的分钟
      const minutes = Math.floor((totalSeconds % 3600) / 60)
      // 计算剩余的秒
      const remainingSeconds = Math.floor(totalSeconds % 60)

      // 格式化为两位数的字符串，如果需要的话
      const formattedHours = String(hours).padStart(2, '0')
      const formattedMinutes = String(minutes).padStart(2, '0')
      const formattedSeconds = String(remainingSeconds).padStart(2, '0')

      // 返回格式化后的字符串
      return `${formattedHours}:${formattedMinutes}:${formattedSeconds}`
    }

    onBeforeUnmount(() => {
      clearInterval(timer.value)
    })
    return {
      tableData,
      TopDigital,
      BottomSwitch,
      TopDigitalList,
      BottomSwitchList,
      TopDigitalcheckboxGroup,
      BottomSwitchcheckboxGroup,
      JsonTmp,
      timer,
      automaticControlcolor,
      manualControlcolor,
      displayRuleText1,
      displayRuleText2,
      automaticControl,
      manualControl,
      handleChangeTopDigital,
      TopDigitalinputBlur,
      handleChangeBottomSwitch,
      BottomSwitchinputBlur,
      changeEvent
    }
  }
}
</script>

<style>
.indexTable {
  width: 100%;
  border-collapse: collapse;
}
.indexTH,
.indexTD {
  border: 1px solid #dddddd;
  padding: 8px;
  text-align: center;
  font-size: 16px;
}
.indexTH {
  background-color: #f2f2f2;
}

/* 修改滚动条的轨道（Track）样式 */
::-webkit-scrollbar {
  width: 3px; /* 设置滚动条宽度 */
  height: 20px;
}

/* 修改滚动条的滑块（Thumb）样式 */
::-webkit-scrollbar-thumb {
  background: skyblue; /* 设置滚动条滑块的背景颜色 */
  border-radius: 5px; /* 设置滚动条滑块的圆角 */
}

/* 修改滚动条的轨道（Track）背景样式 */
::-webkit-scrollbar-track {
  background: white; /* 设置滚动条轨道的背景颜色 */
}

/* 修改滚动条的轨道（Track）背景样式，当鼠标悬停在滚动条上时 */
::-webkit-scrollbar-track:hover {
  background: white; /* 设置悬停时的背景颜色 */
}

.text-overflow {
  text-align: center;
  white-space: nowrap; /* 文字不换行 */
  overflow: hidden; /* 溢出隐藏 */
  text-overflow: ellipsis; /* 溢出时用省略号显示 */
  width: 100%; /* 设置一个具体的宽度或者根据需要调整 */
}
</style>